import 'dart:io';

import 'package:convergence_media/features/app/repository/app_config_repository.dart';
import 'package:convergence_media/features/config/errors/login_errors.dart';
import 'package:convergence_media/features/config/logger/logger.dart';
import 'package:convergence_media/features/user/repositories/token_repository.dart';
import 'package:convergence_media/navigator/app_router.dart';
import 'package:dio/dio.dart';

/// 统一登录认证的拦截器
class NavadminInterceptor extends QueuedInterceptor {
  NavadminInterceptor({
    required TokenRepository tokenRepository,
    required AppRouter appRouter,
    required AppConfigRepository appConfigRepository,
  })  : _tokenRepository = tokenRepository,
        _appRouter = appRouter,
        _appConfigRepository = appConfigRepository;

  final AppConfigRepository _appConfigRepository;
  final AppRouter _appRouter;
  final TokenRepository _tokenRepository;

  @override
  Future<void> onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    logger.t('NavadminInterceptor.onRequest: ${options.uri}');
    if (options.path.startsWith('/sms/send') ||
        options.path.startsWith('/user/mobilelogin')) {
      return handler.next(options);
    }
    final currentHashId = _appConfigRepository.getCurrentHashId();
    if (currentHashId == null) {
      // 未知的处理一律按照未登录计算
      final isLogin = await _appRouter.push<bool>(const LoginRoute()) ?? false;
      if (!isLogin) {
        // 直接拒绝这次请求
        return handler.reject(
          DioException(
            requestOptions: options,
            message: '导航未登录',
          ),
        );
      } else {
        // 移交下一个拦截器处理
        return handler.next(options);
      }
    }
    final isLogin = await _tokenRepository.isLogin(currentHashId);
    if (!isLogin) {
      await _appRouter.push<bool>(const LoginRoute()) ?? false;
      if (!isLogin) {
        // 直接拒绝这次请求
        return handler.reject(
          DioException(
            requestOptions: options,
            message: '导航未登录',
          ),
        );
      } else {
        // 移交下一个拦截器处理
        return handler.next(options);
      }
    }
    super.onRequest(options, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (err.response?.statusCode == HttpStatus.unauthorized) {
      // 交给外部捕获跳转登录处理，拦截器不参与路由跳转
      throw AuthException.unauthorized();
    } else {
      // 除此以外的错误，继续抛出
      super.onError(err, handler);
    }
  }
}
